<template>
  <div style="overflow:hidden;margin-top:20px;">
    <Row style="margin:16px 0;">
      <Page :total="tab6PageCount" show-elevator show-total @on-change="tab6Change" style="float:right;" v-show="tab6TbData.length > 0"/>
    </Row>
      <Table stripe :columns="tab6TbTitle" :data="tab6TbData"></Table>
    <!-- 预览视图tab6  :width="setContentHei" -->
    <Modal v-model="modal6" title="选手视角预览" footer-hide  :width="setContentHei"
        @on-cancel="cancelsmtModal6('formModal6')">
        <div id="display" style="overflow: hidden;min-height:400px;"></div>
    </Modal>
  </div>
</template>

<script>
  import  baseURL from '@/api/index'
  import Guacamole from '@/assets/minejs/all.min'
  import {getSessions,pushNettingData} from '@/api/train.js'
  export default {
    props: ['type', 'poll'], //接受演练竞赛类型
    data() {
      return {
        routeParams:{
          id:this.$route.query.scenarioId,
          prjid:this.$route.query.projectId
        },
        vms4RedBlue: [],
        currPage: 1,
        modal6: false,
        projectId:this.$route.query.projectId,
        tab6move: false,
        guac: '',
        tab6TbData: [],
        tab6PageCount: 0,
        setContentHei:80,
        tab6TbTitle: [
          { title: '虚拟机名称',  key: 'name',placement:'top-left'},
          { title: '昵称',  key: 'userName'},
          { title: '接入方式',  key: 'protocol'},
          { title: '接入IP',  key: 'ip'},
          { title: '接入时间',  key: 'connectTime'},
          {
            title: '操作',
            key: 'operation',
            align: 'center',
            width: 350,
            placement:'top-right',
            action:true,
            render: (h, params) => {
              return h('div', [
                  h('Button', {
                      props: {type: 'info',size: 'small'},
                      style: {marginRight: '5px'},
                      on: {
                        click: () => {
                          this.modal6 = true;
                          this.guac = '';
                          this.preview(params);
                        }
                      }
                  }, '预览'),
              ]);
            }
          }
        ],
      }
    },
    beforeDestroy() {},
    mounted() {
      this.getConnectAllHistories();
    },
    methods: {
      cancelsmtModal6(name){
        let display = document.getElementById("display");
        this.guac.disconnect();
        display.innerHTML = "";
      },
      handleClose(vm){
        //移除保存数据
        this.vms4RedBlue.splice(this.vms4RedBlue.findIndex(item => item.vmId === vm.vmId), 1);
      },
      tab6Change(page) {
        this.currPage = page;
        this.getConnectAllHistories();
      },
      getConnectAllHistories() {
       let _this = this;
        let params = {};
        params = {
          page: _this.currPage,
          rows: 10,
          status: 'connected',
          userType: 'experimenter',
          projectId : _this.projectId,
        }
        getSessions(params).then(data => {
          if(data.data.code==1){
	  				data.data.data.items.map((item)=>{
                if(typeof(item.teamName) == "undefined"){
                  item.teamName='-';
                }
            })
            _this.tab6TbData = data.data.data.items;
            _this.tab6PageCount = data.data.data.total;
	  			}
        })
      },
      preview(params) {
      	let protocol = params.row.protocol;
//      var webURL = `ws://172.18.100.1/api/access/tunnel/webSocket`;
        var webURL = '/api/access/tunnel/webSocket';
        let display = document.getElementById("display");
        if (!!window.WebSocket && window.WebSocket.prototype.send) {
          var tunnel = new Guacamole.WebSocketTunnel(webURL);
        } else { // If no WebSocket, then use HTTP.
          alert('非常抱歉，您的浏览器不支持WebSocket，请安装最新谷歌浏览器再试。')
        }
        this.guac = new Guacamole.Client(
          tunnel
        );
        // 设置缩放比例
//      this.setContentHei = parseInt(params.row.width)+32
//      let widthS = parseInt(params.row.width)
//      let heightH = parseInt(params.row.height)
        // 设置缩放比例
//      this.guac.getDisplay().scale(params.row.width / params.row.height);
        display.appendChild(this.guac.getDisplay().getElement());
        this.disPlayWidth = "";
        //监控元素宽高变化
        let MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
				let observer = new MutationObserver((mutationList, observer) => {
					if(this.disPlayWidth && (this.disPlayWidth == this.guac.getDisplay().getWidth())){
						return
					}else{
						this.disPlayWidth = this.guac.getDisplay().getWidth();
					}
					console.log(mutationList);
					let width = mutationList[0].target.offsetWidth;
					let height = mutationList[0].target.offsetHeight;
					this.setViewSize(width,height,protocol);
				});
        observer.observe(this.guac.getDisplay().getElement(),{attributes:true,attributeFilter:['style'],attributeOldValue:true});
        // Error handler
        this.guac.onerror = function(error){
          console.log(error);
        };
        // token改为recordId,recordId接口查,取第一个的id(状态)
        var width = params.row.width; //localStorage.vncWidth;
        var height = params.row.height; //localStorage.vncHeight;
        var recordId = params.row.id; //localStorage.recordId;
        var token = params.row.token;
        // Connect
        var paramStr = 'sessionId=' + recordId +
          '&width=' + width +
          '&height=' + height + '&observer=true';
        this.guac.connect(paramStr);
        // Disconnect on close
        window.onunload = function() {
          this.guac.disconnect();
        }
      },
      setViewSize(width,height,protocol){
      	let maxWidth = document.documentElement.clientWidth * 0.8;
				let maxHeight = document.documentElement.clientHeight * 0.9;
				if(width > maxWidth){
					let wRadio = maxWidth / width;
					if(this.setContentHei == width * (wRadio)){
						return;
					}
					this.setContentHei = width * (wRadio) + 32;
					if(this.guac.getDisplay().getWidth()){
						this.guac.getDisplay().scale(maxWidth / this.guac.getDisplay().getWidth());
					}else{
						this.guac.getDisplay().scale(wRadio);
					}
				}else{
					if(protocol == 'ssh'){
						this.setContentHei = width + 32
					}else{
						let displayWidth = this.guac.getDisplay().getWidth();
						if(displayWidth){
							this.setContentHei = displayWidth + 32
						}else{
							this.setContentHei = width + 32
						}
						this.guac.getDisplay().scale(1);
					}
				}
      },
      changeView(params) {
        let _this = this;
        let paras = {};
        paras.dname = params.row.instanceName;
        paras.dacc = params.row.id;
        paras.macro = _this.macro;
        paras.type = 'switchCamera';
        paras.vmId = params.row.vmId;
        paras.width = params.row.width;
        paras.height = params.row.height;
        paras.teamName = params.row.teamName;
        paras.userName = params.row.userName;
        paras.connectTime = params.row.connectTime;
        paras.vmName = params.row.name;
        let action = [];
        if (_this.tab6move) {
          action.push('move');
          action.push('screen');
        } else {
          action.push('screen');
        }
        paras.action = action;
        if (_this.macro == 0) {
          if (_this.vms4RedBlue.length == 2) {
            _this.vms4RedBlue[0] = _this.vms4RedBlue[1];
            _this.vms4RedBlue.splice(1, 1);
          }
          _this.vms4RedBlue.push(paras);
        } else if (_this.macro == 1) {
          _this.vms4RedBlue = [];
        }
        paras.projectId = _this.projectId;
        pushNettingData(paras).then(data => {
          if (data.code != '1') {
            _this.$Message.warning(data.message);
          } else {
            _this.$Message.info('操作成功');
          }
        })
      },
      getTeams() {
        let _this = this;
        axios({
          url: 'director/attack/teams?projectId=' + _this.nowUsePrjId,
          method: 'get'
        }).then(function(response) {
          if (response.code != '1') {
            _this.$Message.warning(response.message);
          } else {
            _this.tab7TbData = response.data;
          }
        });
      },
    }
  }
</script>

<style>
  .drillsTable .ivu-poptip-body {
    text-align: left !important;
  }
  .scenesHeader {
    margin-bottom: 16px;
  }
  .drillTables {
    min-height: 300px;
  }
  .drillsTable.ivu-table-wrapper {
    overflow: inherit;
  }
</style>
<style scoped>
  .Titles {
    background: #eeeeee;
    margin: 16px auto;
    padding: 10px 0;
  }
  .targetHeader {
    margin-bottom: 10px;
  }
</style>
